/*
 * Copyright 2014 Soichiro Kashima
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tsingteng.cosfun.ui.mine.tab;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.nineoldandroids.view.ViewHelper;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.AppContext;
import com.tsingteng.cosfun.bean.BaseDataBean;
import com.tsingteng.cosfun.bean.FollowBean;
import com.tsingteng.cosfun.bean.PlayBean;
import com.tsingteng.cosfun.bean.VidePersonBean;
import com.tsingteng.cosfun.callback.AppListener;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.ui.cosfun.PlayActivity;
import com.tsingteng.cosfun.ui.cosfun.contract.PersonWorkContract;
import com.tsingteng.cosfun.ui.cosfun.presenter.PersonWorkPresenter;
import com.tsingteng.cosfun.ui.message.geneal.PlayAdapter;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.ui.mine.PersonTabBaseFragment;
import com.tsingteng.cosfun.ui.mine.adapter.CommonAdapter;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.widget.ObservableListView;
import com.tsingteng.cosfun.widget.flexible.CosfunListView;
import com.tsingteng.cosfun.widget.flexible.ScrollUtils;

import java.util.ArrayList;
import java.util.List;

import static com.tsingteng.cosfun.ui.mine.HomeMineFragment.USERID;

/**
 * author :zhikuan
 * Date:18-8-20
 */
public class PersonTabListVideoFragment extends PersonTabBaseFragment<ObservableListView> implements PlayAdapter.OnAdapterFunctionListener, PersonWorkContract.IPersonWorkrView, CosfunListView.GListViewListener {
    private PersonWorkPresenter personWorkPresenter;
    private int pageNo = 0;
    private String showType = "1";
    private long userId;
    private int pageSize = 0;
    //    private CommonAdapter<List<VidePersonBean.Data>> mAdapter;
    private CommonAdapter<List<VidePersonBean.Data>> mAdapter;
    private TextView emptyView;
    ObservableListView listView;
    private boolean mIsRefreshing = false;


    public static PersonTabListVideoFragment newInstance(String type) {
        PersonTabListVideoFragment hf = new PersonTabListVideoFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        hf.setArguments(args);
        return hf;
    }


    int flexibleSpaceImageHeight;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_person_baselsit_layout, container, false);
        emptyView = view.findViewById(R.id.text_empty);
        listView = (ObservableListView) view.findViewById(R.id.scroll);
        listView.setOnTouchListener((view12, motionEvent) -> {
            if (mIsRefreshing) {
                return true;
            } else {
                return false;
            }
        });
        flexibleSpaceImageHeight = getResources().getDimensionPixelSize(R.dimen.dp_300);

        View paddingView = new View(getContext());
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, flexibleSpaceImageHeight);
        paddingView.setLayoutParams(layoutParams);
        paddingView.setClickable(false);
        listView.addHeaderView(paddingView);
        listView.setPullLoadEnable(true);
        listView.setText(getResources().getString(R.string.loading));
        listView.setPullRefreshEnable(false);
        listView.setCListViewListener(this);
        personWorkPresenter = new PersonWorkPresenter(this);
        mAdapter = new CommonAdapter<List<VidePersonBean.Data>>(getContext(), null, R.layout.item_video_layout) {
            @Override
            public void convert(ViewHolder helper, List<VidePersonBean.Data> item, int positon) {
                if (item == null)
                    return;
//                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) helper.getConvertView().getLayoutParams();
                if (positon == 0 && userId == LogonUtils.getProFildId()) {
//                    params.topMargin = (int) getResources().getDimension(R.dimen.dp_10);
                    helper.getConvertView().setPadding(0, (int) getResources().getDimension(R.dimen.dp_12), 0, 0);
                } else {
                    helper.getConvertView().setPadding(0, (int) getResources().getDimension(R.dimen.dp_2), 0, 0);
//                    params.topMargin = (int) getResources().getDimension(R.dimen.dp_2);
                }
//                helper.getConvertView().setLayoutParams(params);

                ImageView imageView1 = helper.getView(R.id.image1);
                ImageView imageView2 = helper.getView(R.id.image2);
                ImageView imageView3 = helper.getView(R.id.image3);
                TextView textView1 = helper.getView(R.id.tv_watch_num1);
                TextView textView2 = helper.getView(R.id.tv_watch_num2);
                TextView textView3 = helper.getView(R.id.tv_watch_num3);
                TextView mTvDraf = helper.getView(R.id.tv_draf);
                imageView1.setVisibility(View.GONE);
                imageView2.setVisibility(View.GONE);
                imageView3.setVisibility(View.GONE);
                textView1.setVisibility(View.GONE);
                textView2.setVisibility(View.GONE);
                textView3.setVisibility(View.GONE);
                mTvDraf.setVisibility(View.GONE);
                if (TextUtils.equals(showType, "1")) {
                    textView1.setCompoundDrawablePadding(4);
//                    textView1.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_icon),null,null,null);
                    textView2.setCompoundDrawablePadding(4);
//                    textView2.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_icon),null,null,null);
                    textView3.setCompoundDrawablePadding(4);
//                    textView3.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_icon),null,null,null);
                }else {
                    textView1.setCompoundDrawablePadding(4);
//                    textView1.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_icon),null,null,null);
                    textView2.setCompoundDrawablePadding(4);
//                    textView2.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_icon),null,null,null);
                    textView3.setCompoundDrawablePadding(4);
//                    textView3.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_icon),null,null,null);
                }
                switch (item.size()) {
                    case 1:
                        if (positon == 0 && item.get(0).isDrafts) {//草稿箱
                            if (!TextUtils.isEmpty(AppContext.getDraftsCover())) {
                                ImageUtils.LoadImage(getContext(), AppContext.getDraftsCover(), imageView1);
                            }
                            mTvDraf.setVisibility(View.VISIBLE);
                            textView1.setVisibility(View.GONE);
                            imageView1.setVisibility(View.VISIBLE);
                        } else {
                            setImage(imageView1, item.get(0).videoGifUrl, item.get(0).videoCverUrl);
                            if (TextUtils.equals(showType,"1")) {
                                setText(textView1, item.get(0).likeCount + "",item.get(0).isLike);
                            }else {
                                setText(textView1, item.get(0).likeCount + "",item.get(0).isLike);
                            }
                        }
                        break;
                    case 2:
                        if (positon == 0 && item.get(0).isDrafts) {//草稿箱
                            if (!TextUtils.isEmpty(AppContext.getDraftsCover())) {
                                ImageUtils.LoadImage(getContext(), AppContext.getDraftsCover(), imageView1);
                            }
                            mTvDraf.setVisibility(View.VISIBLE);
                            textView1.setVisibility(View.GONE);
                            imageView1.setVisibility(View.VISIBLE);
                        } else {
                            setImage(imageView1, item.get(0).videoGifUrl, item.get(0).videoCverUrl);
                            setText(textView1, TextUtils.equals("1",showType) ?item.get(0).likeCount + "":item.get(0).likeCount+"",item.get(0).isLike);
                        }
                        setImage(imageView2, item.get(1).videoGifUrl, item.get(1).videoCverUrl);
                        setText(textView2, TextUtils.equals("1",showType) ?item.get(1).likeCount + "":item.get(1).likeCount+"",item.get(1).isLike);
                        break;
                    case 3:
                        if (positon == 0 && item.get(0).isDrafts) {//草稿箱
                            if (!TextUtils.isEmpty(AppContext.getDraftsCover())) {
                                ImageUtils.LoadImage(getContext(),AppContext.getDraftsCover(),imageView1);
                            }
                            mTvDraf.setVisibility(View.VISIBLE);
                            textView1.setVisibility(View.GONE);
                            imageView1.setVisibility(View.VISIBLE);
                        } else {
                            setImage(imageView1, item.get(0).videoGifUrl, item.get(0).videoCverUrl);
                            setText(textView1, TextUtils.equals("1",showType) ?item.get(0).likeCount + "":item.get(0).likeCount+"",item.get(0).isLike);
                        }
                        setImage(imageView2, item.get(1).videoGifUrl, item.get(1).videoCverUrl);
                        setText(textView2, TextUtils.equals("1",showType) ?item.get(1).likeCount + "":item.get(1).likeCount+"",item.get(1).isLike);
                        setImage(imageView3, item.get(2).videoGifUrl, item.get(2).videoCverUrl);
                        setText(textView3, TextUtils.equals("1",showType) ?item.get(2).likeCount + "":item.get(2).likeCount+"",item.get(2).isLike);
                        break;
                }
                imageView1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (userId == LogonUtils.getProFildId() && "1".equals(showType)
                                && item.get(0).isDrafts) {//草稿箱
                            Navigate.startDrafts(getActivity());
                            return;
                        }
//                        int mPostion1 = positon * 3 - item.get(0).lastPageCount;
                        int mPostion1 = positon * 3;
                        if (userId == LogonUtils.getProFildId() && "1".equals(showType)
                                && AppContext.isHaveDrafts()) {
                            mPostion1--;
                        }
                        Intent intent = new Intent(getActivity(), PlayActivity.class);
                        intent.putExtra("type", 2);
                        intent.putExtra("id", item.get(0).id);
                        intent.putExtra("userId", userId);
                        intent.putExtra("position", mPostion1);
                        intent.putExtra("pageNo", item.get(0).currentPage);
                        intent.putExtra("showType", showType);
                        getActivity().startActivity(intent);
                    }
                });
                imageView2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        int mPostion2 = positon * 3 + 1 - item.get(1).lastPageCount;
                        int mPostion2 = positon * 3 + 1;
                        if (userId == LogonUtils.getProFildId() && "1".equals(showType)
                                && AppContext.isHaveDrafts()) {
                            mPostion2--;
                        }
                        Intent intent = new Intent(getActivity(), PlayActivity.class);
                        intent.putExtra("type", 2);
                        intent.putExtra("id", item.get(1).id);
                        intent.putExtra("userId", userId);
                        intent.putExtra("position", mPostion2);
                        intent.putExtra("pageNo", item.get(1).currentPage);
                        intent.putExtra("showType", showType);

                        getActivity().startActivity(intent);
                    }
                });
                imageView3.setOnClickListener(view1 -> {
//                        int mPostion3 = positon * 3 + 2 - item.get(2).lastPageCount;
                    int mPostion3 = positon * 3 + 2;
                    if (userId == LogonUtils.getProFildId() && "1".equals(showType)
                            && AppContext.isHaveDrafts()) {
                        mPostion3--;
                    }
                    Intent intent = new Intent(getActivity(), PlayActivity.class);
                    intent.putExtra("type", 2);
                    intent.putExtra("id", item.get(2).id);
                    intent.putExtra("userId", userId);
                    intent.putExtra("position", mPostion3);
                    intent.putExtra("pageNo", item.get(2).currentPage);
                    intent.putExtra("showType", showType);

                    getActivity().startActivity(intent);
                });


            }
        };
        listView.setAdapter(mAdapter);
        listView.setTouchInterceptionViewGroup((ViewGroup) view.findViewById(R.id.fragment_root));

        Bundle args = getArguments();
        if (args != null && args.containsKey(ARG_SCROLL_Y)) {
            final int scrollY = args.getInt(ARG_SCROLL_Y, 0);
            ScrollUtils.addOnGlobalLayoutListener(listView, new Runnable() {
                @SuppressLint("NewApi")
                @Override
                public void run() {
                    int offset = scrollY % flexibleSpaceImageHeight;
                    listView.setSelectionFromTop(0, -offset);
                }
            });
            updateFlexibleSpace(scrollY, view);
        } else {
            updateFlexibleSpace(0, view);
        }

        listView.setScrollViewCallbacks(this);

        updateFlexibleSpace(0, view);

        if (args != null && args.containsKey(TYPE)) {
            showType = args.getString(TYPE);
        }
        if (args != null && args.containsKey(USERID)) {
            userId = args.getLong(USERID);
        }
        refreshData();
        return view;
    }

    public void refreshData() {
        mAdapter.clearData();
        pageNo = 1;
        Log.i("showType", showType);
//        if (AppContext.isHaveDrafts()) {
//            pageSize = 8;
//        }else {
//            pageSize = 9;
//        }
        personWorkPresenter.getWorkList(userId, "1", showType, pageNo + "", Config.PAGE_SIZE + "", "");

    }

    public void setRefresh(boolean boo) {
        this.mIsRefreshing = boo;
    }

    public void refreshData(int id) {
        userId = id;
        if (null !=mAdapter) {
            mAdapter.clearData();
        }
        pageNo = 1;
        Log.i("showType", showType);
        try{
            if (AppContext.isHaveDrafts()) {
                pageSize = 8;
            }else {
                pageSize = 9;
            }
            personWorkPresenter.getWorkList(userId, "1", showType, pageNo + "", Config.PAGE_SIZE + "", "");
        }catch (NullPointerException e) {
        }


    }

    public void setText(TextView textView, String text, int is_like) {
        if (textView.getVisibility() != View.VISIBLE) {
            textView.setVisibility(View.VISIBLE);
        }
        if (null == getContext()) {
            return;
        }
        if (TextUtils.equals("0", text)) {
            textView.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_icon), null, null, null);
        } else {
            if (1 == is_like) {
                textView.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_pink_icon), null, null, null);
            } else if (-1 == is_like) {
                textView.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.great_icon), null, null, null);
            }
        }
        if (textView != null && !text.isEmpty())
            textView.setText(text);
    }

    private void setImage(ImageView imageView, String gif, String videoCverUrl) {
        imageView.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(gif)) {
            ImageUtils.LoadUserVideoImage(getContext(), gif, imageView);
            return;
        }
        if (!TextUtils.isEmpty(videoCverUrl)) {
            ImageUtils.LoadUserVideoImage(getContext(), videoCverUrl, imageView);
        }
    }


    @Override
    public void getFollowResult(FollowBean followBean, int position) {

    }

    public void showParagraphData(PlayBean data) {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdapter != null) {
//            List<List<VidePersonBean.Data>> data = mAdapter.getData();
//            if (data!= null && data.size()>0 && TextUtils.equals(showType,"1")) {
//                if (AppContext.isHaveDrafts() && !data.get(0).get(0).isDrafts) {
//                    List<VidePersonBean.Data> list = new ArrayList<>();
//                    VidePersonBean.Data d = new VidePersonBean.Data();
//                    d.isDrafts = true;
//                    list.add(d);
//                    data.add(0,list);
//                    mAdapter.addData(data);
//                }else {
//                    if (data.get(0).get(0).isDrafts) {
//                        data.remove(0);
//                        mAdapter.addData(data);
//                    }
//                }
//            }
//            refreshData();
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void shoWorkData(VidePersonBean data) {
        setRefresh(false);
        listView.stopLoadMore();
        if (isAdded()) {
            listView.setText(getResources().getString(R.string.listview_footer_hint_normal));
        }
        if (data == null || data.data == null || data.data.size() == 0) {
            if (isEmpty()) {
                if ("1".equals(showType)) {//我的作品
                    if (AppContext.isHaveDrafts() && userId == LogonUtils.getProFildId()) {
                        List<List<VidePersonBean.Data>> all = new ArrayList<>();
                        List<VidePersonBean.Data> list = new ArrayList<>();
                        VidePersonBean.Data d = new VidePersonBean.Data();
                        d.isDrafts = true;
                        list.add(d);
                        all.add(list);
                        mAdapter.addData(all);
                        emptyView.setVisibility(View.GONE);
                    } else {
                        mAdapter.clear();
                        emptyView.setText("TA还没有创作~");
                        emptyView.setVisibility(View.VISIBLE);
                    }
                } else {
                    mAdapter.clear();
                    emptyView.setVisibility(View.VISIBLE);
                    emptyView.setText("TA还没有喜欢的创作~");
                }
                listView.setFooterText("");
            } else {
                emptyView.setVisibility(View.GONE);
                listView.setFooterText("到底啦~");

            }
            return;
        }
//        if (data.data.size() <= 10) {//不可下拉
//            listView.setFooterText("到底啦~");
//        }
        //有草稿放第一位
        if ("1".equals(showType)
                && AppContext.isHaveDrafts()
                && userId == LogonUtils.getProFildId() && pageNo == 1) {
            VidePersonBean.Data d = new VidePersonBean.Data();
            d.isDrafts = true;
            data.data.add(0, d);
        }
        //拿到数据后设置当前项的页数归属
        for (VidePersonBean.Data item : data.data) {
            item.currentPage = pageNo;
            item.lastPageCount = mAdapter.getCount();
        }
        List<VidePersonBean.Data> dataNew = new ArrayList<>();
        if (mAdapter.getData() != null && mAdapter.getData().size() > 0) {
            List<List<VidePersonBean.Data>> adapterList = mAdapter.getData();
            List<VidePersonBean.Data> lastData = adapterList.get(adapterList.size() - 1);
            if (lastData.size() != 3) {
                mAdapter.removeData(lastData);
                dataNew.addAll(lastData);
            }
        }

        dataNew.addAll(data.data);
        int allSize = dataNew.size();
        int realSize = allSize / 3;
        int last = allSize % 3;
        if (last > 0) {
            realSize++;
        }
        Log.i("zhikuan", allSize + "   " + realSize + "   " + last);
        List<List<VidePersonBean.Data>> allData = new ArrayList<>();
        for (int i = 0; i < realSize; i++) {

            List<VidePersonBean.Data> dataList = new ArrayList<>();
            if (i == realSize - 1) {
                if (last == 1) {
                    dataList.add(dataNew.get(i * 3));
                } else if (last == 2) {
                    dataList.add(dataNew.get(i * 3));
                    dataList.add(dataNew.get(i * 3 + 1));
                } else {
                    dataList.add(dataNew.get(i * 3));
                    dataList.add(dataNew.get(i * 3 + 1));
                    dataList.add(dataNew.get(i * 3 + 2));
                }
            } else {
                dataList.add(dataNew.get(i * 3));
                dataList.add(dataNew.get(i * 3 + 1));
                dataList.add(dataNew.get(i * 3 + 2));

            }
            allData.add(dataList);

        }
        pageNo++;
        mAdapter.addData(allData);
        if (isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
            emptyView.setText("TA还没有创作~");
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }


    private boolean isEmpty() {

        int count = mAdapter.getCount();
        if (count > 0) {//有数据

            return false;
        } else {
            return true;
        }
    }

    @Override
    public void showPraiseResult(Integer data, int position) {

    }

    @Override
    public void ShowNotLiketResult(BaseDataBean<String> dataBean, int position) {

    }

    @Override
    public void showDelResult(BaseDataBean<String> dataBean, int position) {

    }

    @Override
    public void showCancelPullBlack(int data) {

    }

    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }



    @SuppressWarnings("NewApi")
    @Override
    public void setScrollY(int scrollY, int threshold) {
        View view = getView();
        if (view == null) {
            return;
        }
        ObservableListView listView = (ObservableListView) view.findViewById(R.id.scroll);
        if (listView == null) {
            return;
        }
        View firstVisibleChild = listView.getChildAt(0);
        if (firstVisibleChild != null) {
            int offset = scrollY;
            int position = 0;
            if (threshold < scrollY) {
                int baseHeight = firstVisibleChild.getHeight();
                position = scrollY / baseHeight;
                offset = scrollY % baseHeight;
            }
            listView.setSelectionFromTop(position, -offset);
        }
    }

    @Override
    protected void updateFlexibleSpace(int scrollY, View view) {
        View listBackgroundView = view.findViewById(R.id.list_background);
        ViewHelper.setTranslationY(listBackgroundView, Math.max(0, -scrollY + flexibleSpaceImageHeight));
        List<android.support.v4.app.Fragment> listFragment = getActivity().getSupportFragmentManager().getFragments();
        for (int i = 0; i < listFragment.size(); i++) {
            android.support.v4.app.Fragment fragment = listFragment.get(i);
            if (fragment instanceof HomeMineFragment) {
                ((HomeMineFragment) fragment).onScrollChanged(scrollY, (ObservableListView) view.findViewById(R.id.scroll));

            }
        }
    }

    @Override
    public void onMoreClick(PlayBean.PlayListBean item) {

    }

    @Override
    public void onAttentionClick(PlayBean.PlayListBean item, TextView textView, ImageView imageView) {

    }

    @Override
    public void onFilmDrawClick(PlayBean.PlayListBean item) {

    }

    @Override
    public void onGreatClick(PlayBean.PlayListBean item, ImageView imageView, TextView greatNum) {

    }

    @Override
    public void onCommentClick(PlayBean.PlayListBean item) {

    }

    @Override
    public void onShareClick(PlayBean.PlayListBean item, TextView shareNum) {
        hideLoading();
        shareNum.setText(item.getForwardCount() + 1);
        mAdapter.notifyDataSetChanged();
    }


    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        if (AppContext.isHaveDrafts()) {
            pageSize = 8;
        } else {
            pageSize = 9;
        }
        personWorkPresenter.getWorkList(userId, "1", showType, pageNo + "", Config.PAGE_SIZE + "", "");
    }

    @Override
    public void onDeleteItem(int index) {

    }
}
